<?php


namespace app\api\model;

use app\api\controller\Code;
use think\Db;
use think\Model;

/**
 * 会议笔记
 * Class NotesModel
 * @package app\api\model
 *
 */
class NotesModel extends Model
{

    /**
     * 设置表名
     * @var string
     */
    protected $table = 'ah_notes';

    /**
     *
     * 会议笔记信息
     */
    public static function notesInfo($params){

        $where =[];
        if (isset($params['discussion_at']) && $params['discussion_at'] != ''){

            $where[] = ['n.discussion_at','eq',$params['discussion_at']];
        }
        $data['data'] = self::alias('n')->where($where)
            ->where(['n.case_id'=>$params['id'],'type'=>$params['type']])
            ->join('ah_case c','n.case_id = c.id')
            ->field('n.id,c.name,c.sex,c.age,n.discussion_at,n.expert_ids,n.case_review,n.expert_suggest,n.notes,n.meeting_id')
            ->order('n.id desc')
            ->limit(1)
            ->select()->each(function ($item)use ($params){

                if ($params['type'] == 0){

                    $item['meeting_url'] = MeetingModel::where(['id'=>$item['meeting_id']])->value('meeting_url');
                }else{
                    $item['meeting_url'] = '';
                }

                if ($item['case_review']){

                    $item['case_review'] = json_decode($item['case_review'],true);
                }
                if ($item['expert_suggest']){

                    $item['expert_suggest'] = json_decode($item['expert_suggest'],true);
                }
                if ($item['expert_ids']){

                    $item['expert_info'] = UserModel::whereIn('id',$item['expert_ids'])->field('id,nickname,head_img')->select();
                }
            })->toArray();
        $data['discussion_at'] = self::alias('n')
            ->where(['n.case_id'=>$params['id'],'type'=>$params['type']])
            ->join('ah_case c','n.case_id = c.id')
            ->order('n.id desc')
            ->column('discussion_at');
        return $data;
    }

    /**
     *
     * 保存会议笔记
     */
    public static function notesAdd($params){

        $notes = [

            'user_id'=>$params['user_id'],
            'case_id'=>$params['case_id'],
            'meeting_id'=>isset($params['meeting_id']) ? $params['meeting_id'] : 0,
            'type'=>$params['type'],
            'expert_ids'=>isset($params['meeting_id']) ? MeetingModel::where(['id'=>$params['meeting_id']])->value('expert_ids') : '',
            'discussion_at'=>$params['discussion_at'],
            'case_review'=>json_encode($params['case_review']),
            'expert_suggest'=>json_encode($params['expert_suggest']),
            'notes'=>$params['notes'],

        ];
        if (isset($params['id']) && $params['id'] > 0){

            return self::where(['id'=>$params['id']])->update($notes);
        }
        return self::insert($notes);
    }




}